import { Injectable, Body, Res, UnauthorizedException } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { UsersService } from '../users/users.service';
import * as bcrypt from 'bcrypt';
import { User } from '../users/entities/user.entity';

@Injectable()
export class AuthService {
  constructor(
    private usersService: UsersService,
    private jwtService: JwtService,
  ) {}

  async validateUser(username: string, password: string): Promise<any> {
    const user = await this.usersService.findOne(username);
    if (!user) {
      throw new UnauthorizedException('用户不存在');
    }
    
    const isPasswordValid = await bcrypt.compare(password, user.password);
    // const isPasswordValid = password === user.password;
    if (!isPasswordValid) {
      throw new UnauthorizedException('密码错误');
    }

    const { password: _, ...result } = user;
    return result;
  }

  async login(user) {
    try {
      const findUser = await this.usersService.findOne(user.username);

      const payload = { 
        username: user.username,
        role: user.role,
      };
      
      const access_token = this.jwtService.sign(payload);

      const returnData: { access_token: string, user: any } = {
        access_token,
        user: null,
      };

      if (findUser) {
        const { id, name, username, role } = findUser;
        returnData.user = {
          id, name, username, role
        };
      }
      return returnData;
            
    } catch (error) {
        console.error(error)
    }
  }

  async refreshToken(user: any) {
    const payload = { 
      username: user.username, 
      sub: user.id,
      role: user.role 
    };
    
    return {
      access_token: this.jwtService.sign(payload)
    };
  }
} 